package logic

import (
	"context"
	"errors"
	"user_svc/models"
	"user_svc/pkg"

	"user_svc/internal/svc"
	"user_svc/user"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdatePwdLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdatePwdLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdatePwdLogic {
	return &UpdatePwdLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UpdatePwdLogic) UpdatePwd(in *user.UpdatePwdRequest) (*user.UpdatePwdResponse, error) {
	// todo: add your logic here and delete this line
	var err error
	var u models.User
	u.ID = uint(in.UserId)

	if in.NewPwd != in.SurePwd {
		logx.Error("两次密码不一致")
		return nil, errors.New("两次密码不一致")
	}

	if err = u.GetUserById(); err != nil {
		logx.Error("获取用户信息失败")
		return nil, errors.New("获取用户信息失败")
	}

	if u.Password == pkg.Md5(in.NewPwd) {
		logx.Error("新密码不能与旧密码一致")
		return nil, errors.New("新密码不能与旧密码一致")
	}

	u.Password = pkg.Md5(in.NewPwd)

	if err = u.UpdatePwd(); err != nil {
		logx.Error("密码修改失败")
		return nil, errors.New("密码修改失败")
	}

	return &user.UpdatePwdResponse{
		UserId: int64(u.ID),
	}, nil
}
